package com.apimanage.monitor.service.impl;

import com.apimanage.monitor.entity.ApiLog;
import com.apimanage.monitor.entity.ApiStatistics;
import com.apimanage.monitor.mapper.ApiLogMapper;
import com.apimanage.monitor.mapper.ApiStatisticsMapper;
import com.apimanage.monitor.service.MonitorService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 监控服务实现类
 * 实现API调用日志记录和统计功能
 */
@DubboService
public class MonitorServiceImpl implements MonitorService {

    @Autowired
    private ApiLogMapper apiLogMapper;

    @Autowired
    private ApiStatisticsMapper apiStatisticsMapper;

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public boolean recordApiLog(ApiLog apiLog) {
        return apiLogMapper.insert(apiLog) > 0;
    }

    public List<ApiLog> getApiLogPage(Map<String, Object> params) {
        return apiLogMapper.selectApiLogPage(params);
    }

    public List<ApiLog> getApiLogByApiId(Long apiId, Date startTime, Date endTime) {
        return apiLogMapper.selectByApiId(apiId, startTime, endTime);
    }

    public List<ApiLog> getApiLogByUserId(Long userId, Date startTime, Date endTime) {
        return apiLogMapper.selectByUserId(userId, startTime, endTime);
    }

    @Override
    public void updateApiStatistics(Long apiId, Integer status, Long costTime) {
        String today = dateFormat.format(new Date());
        ApiStatistics statistics = apiStatisticsMapper.selectTodayStatistics(apiId, today);

        if (statistics == null) {
            // 创建新的统计记录
            statistics = new ApiStatistics();
            statistics.setApiId(apiId);
            statistics.setStatisticsDate(today);
            statistics.setTotalCalls(1);
            statistics.setSuccessCalls(status == 1 ? 1 : 0);
            statistics.setFailCalls(status == 0 ? 1 : 0);
            statistics.setAvgResponseTime(Double.valueOf(costTime));
            statistics.setCreateTime(new Date());
            statistics.setUpdateTime(new Date());
            apiStatisticsMapper.insert(statistics);
        } else {
            // 更新现有统计记录
            int newTotalCalls = statistics.getTotalCalls() + 1;
            int newSuccessCalls = statistics.getSuccessCalls() + (status == 1 ? 1 : 0);
            int newFailCalls = statistics.getFailCalls() + (status == 0 ? 1 : 0);
            double newAvgResponseTime = ((statistics.getAvgResponseTime() * statistics.getTotalCalls()) + costTime) / newTotalCalls;

            UpdateWrapper<ApiStatistics> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", statistics.getId())
                    .set("total_calls", newTotalCalls)
                    .set("success_calls", newSuccessCalls)
                    .set("fail_calls", newFailCalls)
                    .set("avg_response_time", newAvgResponseTime)
                    .set("update_time", new Date());
            apiStatisticsMapper.update(null, updateWrapper);
        }
    }

    public List<ApiStatistics> getApiStatisticsPage(Map<String, Object> params) {
        return apiStatisticsMapper.selectStatisticsPage(params);
    }

    public List<ApiStatistics> getApiStatisticsByApiIdAndDateRange(Long apiId, String startDate, String endDate) {
        return apiStatisticsMapper.selectByApiIdAndDateRange(apiId, startDate, endDate);
    }

    public Map<String, Object> getApiOverviewStatistics(List<Long> apiIds, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>();
        // 这里可以实现API调用概览统计的逻辑
        // 例如：统计总调用次数、成功率、平均响应时间等
        return result;
    }

}